//
//  RegisteredViewController.m
//  liangyi
//
//  Created by 张水 on 16/12/19.
//  Copyright © 2016年 yswh. All rights reserved.
//

#import "RegisteredViewController.h"
#import "AppHeader.h"
@interface RegisteredViewController ()

@property(nonatomic,strong) CustomTextField *userPhone;

@property(nonatomic,strong) CustomTextField *userVerity;

@property(nonatomic,strong) CustomTextField *userPassWord;

@property(nonatomic,strong) UIButton        *btnVerity;

@property (strong, nonatomic) UIButton      *btnRegister;

@property(nonatomic,strong) UIButton *showSecureBtn;

@property (strong, nonatomic) NSTimer       *timer;

@property (assign, nonatomic) NSInteger     index;

@property (nonatomic, strong) NSString      *strPhone;

@end

@implementation RegisteredViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupData];
    [self setupUI];
    [self setNav];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.timer invalidate];
}

-(void)setupData {
    self.index = 60;
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
////    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
////    self.navigationController.navigationBar.translucent = NO;
////    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
////    self.navigationController.navigationBar.shadowImage = [UIImage new];
//}
//-(void)viewWillDisappear:(BOOL)animated{
//    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.translucent = NO;
//}


#pragma mark - Data & UI

-(void)setNav{
    self.title = @"注册";
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem  alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(cancelRegidDidClick)];
}


-(void)setupUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.userPhone = [[CustomTextField alloc]init];
    [self.userPhone setLeftTitleFont:[UIFont systemFontOfSize:14]];
    self.userPhone.leftTitle = @"手机号码";
    self.userPhone.keyboardType =  UIKeyboardTypeNumberPad;
    self.userPhone.leftTitleColor = [UIColor ColorWithHex:@"#7d7d7d"];
    self.userPhone.placeholder = @"输入手机号码";
    self.userPhone.validator = [PhoneValidator new];
    [self.userPhone setValue:[UIColor ColorWithHex:@"#a5a5a5"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.userPhone setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    self.userPhone.layer.cornerRadius = 23;
    self.userPhone.layer.borderColor = [UIColor ColorWithHex:@"#efefef"].CGColor;
    self.userPhone.layer.borderWidth = 2;
    [self.view addSubview:self.userPhone];
    [self.userPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(94);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.equalTo(@48);
    }];
    
    UILabel *backLable =[[UILabel alloc]init];
    [self.view addSubview:backLable];
    backLable.backgroundColor = [UIColor ColorWithHex:@"#5ac3d1"];
    [backLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(self.userPhone.mas_height);
        make.width.equalTo(@70);
        make.centerY.equalTo(self.userPhone.mas_centerY);
        make.right.equalTo(self.userPhone.mas_right).offset(-30);
    }];
    
    
    self.btnVerity = [UIButton new];
    [self.btnVerity setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.btnVerity.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.btnVerity setTitleColor:[UIColor ColorWithHex:@"#025d69"] forState:UIControlStateNormal];
    [self.btnVerity.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [self.btnVerity setBackgroundColor:[UIColor ColorWithHex:@"#5ac3d1"]];
    self.btnVerity.layer.cornerRadius = 23;
    [self.btnVerity addTarget:self action:@selector(sendVerityCodeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnVerity];
    [self.btnVerity mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(self.userPhone.mas_height);
        make.width.equalTo(@100);
        make.centerY.equalTo(self.userPhone.mas_centerY);
        make.right.equalTo(self.userPhone.mas_right);
    }];
    
    
    
    
    self.userVerity = [[CustomTextField alloc]init];
    [self.userVerity setLeftTitleFont:[UIFont systemFontOfSize:14]];
    self.userVerity.leftTitle = @"验证码";
    self.userVerity.keyboardType =  UIKeyboardTypeNumberPad;
    self.userVerity.leftTitleColor = [UIColor ColorWithHex:@"#7d7d7d"];
    self.userVerity.placeholder = @"输入验证码";
    [self.userVerity setValue:[UIColor ColorWithHex:@"#a5a5a5"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.userVerity setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    self.userVerity.layer.cornerRadius = 23;
    self.userVerity.layer.borderColor = [UIColor ColorWithHex:@"#efefef"].CGColor;
    self.userVerity.layer.borderWidth = 2;
    [self.view addSubview:self.userVerity];
    [self.userVerity mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userPhone.mas_bottom).offset(25);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.equalTo(@48);
    }];
    
    self.userPassWord = [[CustomTextField alloc]init];
    [self.userPassWord setLeftTitleFont:[UIFont systemFontOfSize:14]];
    self.userPassWord.leftTitle = @"设置密码";
    self.userPassWord.leftTitleColor = [UIColor ColorWithHex:@"#7d7d7d"];
    self.userPassWord.placeholder = @"4-16位密码,建议数字,字母混合使用";
    [self.userPassWord setValue:[UIColor ColorWithHex:@"#a5a5a5"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.userPassWord setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    self.userPassWord.layer.cornerRadius = 23;
    self.userPassWord.layer.borderColor = [UIColor ColorWithHex:@"#efefef"].CGColor;
    self.userPassWord.layer.borderWidth = 2;
    [self.view addSubview:self.userPassWord];
    [self.userPassWord mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userVerity.mas_bottom).offset(25);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.equalTo(@48);
    }];
    
    self.btnRegister = [[UIButton alloc]init];
    self.btnRegister.backgroundColor = [UIColor ColorWithHex:@"#5ac3d1"];
    self.btnRegister.layer.cornerRadius = 23;
    [self.btnRegister setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.btnRegister setTitle:@"注册" forState:UIControlStateNormal];
    [self.btnRegister addTarget:self action:@selector(registerNetwork) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnRegister];
    [self.btnRegister mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userPassWord.mas_bottom).offset(50);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.equalTo(@48);
    }];
    
    self.showSecureBtn = [[UIButton alloc]init];
    [self.view addSubview:self.showSecureBtn];
    [self.showSecureBtn setImage:[UIImage imageNamed:@"unvisible"] forState:UIControlStateNormal];
    [self.showSecureBtn setImage:[UIImage imageNamed:@"visible"] forState:UIControlStateSelected];
    [self.showSecureBtn addTarget:self action:@selector(showAndHidePassword:) forControlEvents:UIControlEventTouchUpInside];
    [self.showSecureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.userPassWord.mas_centerY);
        make.right.equalTo(self.userPassWord.mas_right).offset(-15);
        make.height.with.equalTo(@50);
    }];
    
    
}



-(void)submitYzm{
    
    [self registerTimerAction];
    
    NSString *url = [BASEURL stringByAppendingString:kURL_Sendsend];
    
    NSDictionary *dict= @{@"phone":self.userPhone.text,
                          @"position":@""};
    NSString *jsonString = [NSString dictionaryToJson:dict];
    NSString *AESString = [NSString AES128Encrypt:jsonString];
    NSDictionary *parameters = @{@"parameters":AESString};
    
    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
        
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        NSLog(@"%@", responseObject);
        NSLog(@"验证码");
        if (code == 0) {
             
        }else{
            [CustomProgressHUD showErrorWithStatus:network.errorDescription];
        }
        
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:@"连接失败,请检查您的网络"];
    }];
    
}
-(void)checkPhoenNetwork {
    
    if (![self.userPhone validate]){
        [CustomProgressHUD showErrorWithStatus:self.userPhone.validator.errorMessage];
    }else{
        NSString *url = [BASEURL stringByAppendingString:kURL_Verifyphone];
        NSDictionary *dict = @{@"phone":[NSString stringWithFormat:@"%@",self.userPhone.text]};
        NSString *jsonString = [NSString dictionaryToJson:dict];
        NSString *AESString = [NSString AES128Encrypt:jsonString];
        NSDictionary *parameters = @{@"parameters":AESString};
        
        [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
            NSLog(@"%@",responseObject);
            NSLog(@"校验了");
            NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
            NSInteger code = network.code.integerValue;
            if (code == 0) {
                [self submitYzm];
            }else{
                self.userPhone.text = nil;
                [CustomProgressHUD showErrorWithStatus:network.errorDescription];
                
            }
        } failure:^(id error) {
            [CustomProgressHUD showErrorWithStatus:@"连接失败,请检查您的网络"];
        }];
    }
    
}

-(void)sendVerityCodeAction:(UIButton *)sender{
    [self checkPhoenNetwork];
}
-(void)showAndHidePassword:(UIButton *)sender{
    self.userPassWord.enabled = NO;
    self.userPassWord.secureTextEntry = sender.selected;
    sender.selected = !sender.selected;
    self.userPassWord.enabled = YES;
    [self.userPassWord becomeFirstResponder];
}
-(void)registerTimerAction{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0f * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(timer, ^{
        if (self.index <= 0 ){
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.index = 60;
                self.btnVerity.userInteractionEnabled = YES;
                [self.btnVerity setTitle:@"获取验证码" forState:UIControlStateNormal];
            });
        }else{
            self.index--;
            self.btnVerity.userInteractionEnabled = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.btnVerity setTitle:[NSString stringWithFormat:@"重新发送(%ld)",(long)self.index] forState:UIControlStateNormal];
            });
        }
    });
    dispatch_resume(timer);
}
-(void)registerNetwork{
    
    NSString *url = [BASEURL stringByAppendingString:kURL_Regist];
    NSDictionary *dict = @{@"userPhone":self.userPhone.text,
                           @"checkNo":self.userVerity.text,
                           @"password":self.userPassWord.text};
    NSString *jsonString = [NSString dictionaryToJson:dict];
    NSLog(@"%@",jsonString);
    NSString *AESString = [NSString AES128Encrypt:jsonString];
    NSDictionary *parameters = @{@"parameters":AESString};
    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            [CustomProgressHUD showSuccessWithStatus:@"注册成功"];
            [self executeLogin];
        }else{
            [CustomProgressHUD showErrorWithStatus:network.errorDescription];
        }
    } failure:^(id error) {
        NSLog(@"%@",error);
        [CustomProgressHUD showErrorWithStatus:@"连接失败,请检查您的网络"];
    }];
}
- (void)executeLogin {
    
    
    NSString *url = [BASEURL stringByAppendingString:kURl_Login];
    NSDictionary *dict = @{@"username":self.userPhone.text,
                           @"password":self.userPassWord.text,
                           @"deviceId":ApplicationDelegate.deviceID};
    NSString *jsonString = [NSString dictionaryToJson:dict];
    NSString *AESString = [NSString AES128Encrypt:jsonString];
    NSDictionary *parameters = @{@"parameters":AESString};
    
    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0) {
            UserModel *model = [UserModel mj_objectWithKeyValues:network.dataObject];
            NSLog(@"%@",model.id);
            [UserDefaultsUtlis saveValue:model.id forKey:@"userid"];
            [UserDefaultsUtlis saveValue:model.userPhone forKey:@"userPhone"];
            [Sp_MemberStorage insertMemberWithUserModel:model];
            [self.navigationController  popToRootViewControllerAnimated:YES];
        }else {
            [CustomProgressHUD showErrorWithStatus:network.errorDescription];
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error ];
    }];
}

-(void)cancelRegidDidClick{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
